package pers.w.chaptertalk.ui.search;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.BookThread;
import pers.w.chaptertalk.funs.ChapterThread;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;


public class SearchViewModel extends ViewModel {

    public static class BookInfoLiveDat extends LiveData<BookInfoLiveDat> {
        private ArrayList<BookInfo> info;

        public void setInfo(ArrayList<BookInfo> value) {
            info = value;
            postValue(this);
        }

        public ArrayList<BookInfo> getInfo() {
            return info;
        }
    }

    private BookInfoLiveDat bookInfoLiveDat = new BookInfoLiveDat();

    BookInfoLiveDat getQuery() {
        return bookInfoLiveDat;
    }


    //public static int MY_THREAD_RAN = 666666;

    private HashMap<String, String> bookResources;


    void setBookResources(HashMap<String, String> bookResources) {
        this.bookResources = bookResources;
    }


    public HashMap<String, String> getBookResources() {
        return bookResources;
    }


    Exception getException() {
        return exception;
    }

    void resetException() {
        exception = null;
    }

    Exception exception;

    /**
     * @param fromUriName 从哪个网址搜索
     * @param bookName
     */
    void searchBooks(final String fromUriName, final String bookName) {
        curSearchUrl = bookResources.get(fromUriName) + bookName;
        if (Fun.isDebug()) Log.d("SEARCH", curSearchUrl);

        new BookThread() {
            @Override
            public void run() {
                ArrayList<BookInfo> books = new ArrayList<>();
                try {
                    Document doc;

                    //books.clear();
                    String baseUri = bookResources.get(fromUriName);
                    assert baseUri != null;
                    Map<String,String> cookies = new HashMap<String,String>();
                    cookies.put("96ea880ed537df4929f96ab5a3cbd567","1");
                    cookies    .put("Hm_lvt_498cbbbbe383ddc737350f19322f160b","1622956741");
                    cookies    .put("796ab53acf966fbacf8f078ecd10a9ce","a%3A1%3A%7Bi%3A57684%3Bs%3A31%3A%2271716919%7C%2A%7C%E7%AC%AC68%E7%AB%A0%E4%BC%8A%E4%B8%BD%E8%8E%8E%E7%99%BD%22%3B%7D");
                    cookies     .put("obj","1");
                    cookies      .put("Hm_lpvt_498cbbbbe383ddc737350f19322f160b","1622967545");
                    switch (baseUri) {
                        case "https://www.52bqg.net/modules/article/search.php?searchkey=":
                            byte[] bookNameByte = bookName.getBytes("GBK");
                            StringBuilder url = new StringBuilder();
                            url.append(baseUri);
                            for (int i = 0; i < bookNameByte.length; i++) {
                                url.append(String.format("%%%X", bookNameByte[i]));
                            }
                            doc = Jsoup.connect(url.toString()).timeout(5000).get();
                            if (0 == doc.location().indexOf(baseUri))
                                handle_bqg(books, doc, "div.novelslistss", 0);
                            else {
                                BookInfo book = ChapterThread.handle_bqg(doc, BookThread.BQG1);
                                if (book != null) books.add(book);
                            }
                            break;
                        case "https://www.biqugg.com/modules/article/search.php?searchtype=keywords&searchkey="://
                            doc = Jsoup.connect(curSearchUrl).timeout(5000).get();
                            if (0 == doc.location().indexOf(baseUri)) {//有多本，不会跳网址
                                handle_bqg(books, doc, "div.novelslist2", 1);
                                for (BookInfo bi : books) {
                                    bi.setFieldValue(R.string.info_uri, IReader.资源笔趣阁2+"/xs" + bi.getFieldValue(R.string.info_uri));
                                }
                            } else {
                                BookInfo book = ChapterThread.handle_bqg(doc, BookThread.BQG2);
                                if (book != null) books.add(book);
                            }//只有一本的时候会跳转
                            break;
                        case "https://www.23txt.com/search.php?q="://天籁小说网，网站搜索故障
                            doc = Jsoup.connect(curSearchUrl).timeout(5000).get();
                            handle_tianlai(books, doc);
                            break;
                        case "http://www.biquge.se/case.php?m=search"://
                            Connection conn = Jsoup.connect(baseUri);
                            conn.data("key",bookName)
                                    .cookies(cookies);
                            doc = conn.timeout(5000).post();
                            handle_bqg(books, doc, "div.l", 0);
                            for (BookInfo bi : books) {
                                bi.setFieldValue(R.string.info_uri, IReader.资源笔趣阁3+ bi.getFieldValue(R.string.info_uri));
                            }
                            break;
                        case "https://www.mht.tw/cases.php?m=search":
                            Connection conn1 = Jsoup.connect(baseUri);
                            conn1.data("key",bookName)
                                .cookies(cookies);
                            doc = conn1.timeout(5000).post();
                            handle_bqg(books, doc, "div.l", 0);
                            for (BookInfo bi : books) {
                                bi.setFieldValue(R.string.info_uri, IReader.资源笔趣阁4+ bi.getFieldValue(R.string.info_uri));
                            }
                            break;
                    }
                } catch (IOException e) {
                    exception = e;
                    e.printStackTrace();
                } finally {
                    bookInfoLiveDat.setInfo(books);
                }
            }
        }.start();

    }

    private String curSearchUrl = "";

}